<template>
  <div v-show="$route.name == 'material-multi'">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/material-purchase' }">原料采购单</el-breadcrumb-item>
      <el-breadcrumb-item>批量采购</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <div style="margin-bottom: 20px;">批量采购</div>
      <!-- 搜索与添加区域 -->
      <el-form :model="saveForm"
      :rules="saveFormRules"
      ref="saveFormRef"
      label-width="110px">
        <el-row>
          <el-col :span="7">
            <el-form-item label="日期" prop="default_time" style="width: 300px;">
              <el-date-picker type="date" placeholder="选择日期" v-model="saveForm.default_time">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="17">
            <el-form-item label="供应商" prop="supplier" style="width: 300px;">
              <el-input v-model="saveForm.supplier"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 商品表格 -->
        <el-row>
          <el-card>
             <!-- 搜索与添加区域 -->
             <el-row :gutter="20">
              <el-col :span="4">
                <el-button type="success" @click="showProductAddDialog()">新增</el-button>
              </el-col>
            </el-row>
            <!-- 商品列表区域 -->
            <el-table :data="saveForm.productList" border stripe height="300">
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column label="分类" prop="category"></el-table-column>
              <el-table-column label="商品" prop="goods"></el-table-column>
              <el-table-column label="是否可销售" prop="sellable">
                <template slot-scope="scope">
                  {{scope.row.sellable ? '是' : '否'}}
                </template>
              </el-table-column>
              <el-table-column label="入库价格" prop="price_in"></el-table-column>
              <el-table-column label="入库单位" prop="unit_in"></el-table-column>
              <el-table-column label="售出单位" prop="unit"></el-table-column>
              <el-table-column label="转换比例" prop="conversion"></el-table-column>
              <el-table-column label="入库数量" prop="count_in"></el-table-column>
              <el-table-column label="总价" prop="total_amount"></el-table-column>
              <el-table-column label="备注" prop="comment"></el-table-column>
              <el-table-column label="操作" width="120px">
                <template slot-scope="scope">
                  <!-- 修改按钮 -->
                  <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showProductEditDialog(scope.row, scope.$index)"></el-button>
                  </el-tooltip>
                  <!-- 删除按钮 -->
                  <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteProduct(scope.row)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col>
            <el-button @click="back">返回</el-button>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 保存商品对话框 -->
    <el-dialog :title="isProductAdd ? '新增商品' : '修改商品'" :visible.sync="saveProductDialogVisible" width="70%" @close="saveProductDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="saveProductForm" :rules="saveProductFormRules" ref="saveProductFormRef" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="类型" prop="category_id">
              <el-select v-model="saveProductForm.category_id" popper-class="dropdownbox" style="width:200px" placeholder="请选择品类">
                <el-option v-for="item in categoryList" :label="item.category_name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.category_name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品" prop="goods_id">
              <el-select v-model="saveProductForm.goods_id" popper-class="dropdownbox" style="width:200px" placeholder="请选择商品">
                <el-option v-for="item in goodsList" :label="item.name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否可销售" prop="sellable">
              <el-radio-group v-model="saveProductForm.sellable" disabled>
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库价格" prop="price_in">
              <el-input-number controls-position="right" :precision="2" :step="1" v-model="saveProductForm.price_in" placeholder="请输入价格" style="width:200px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库数量" prop="count_in">
              <el-input-number controls-position="right" :precision="2" :step="1" v-model="saveProductForm.count_in" style="width:200px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价" prop="total_amount">
              <el-input-number controls-position="right" :precision="2" :step="1" v-model="saveProductForm.total_amount" style="width:200px" disabled></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库单位" prop="unit_in">
              <el-input v-model="saveProductForm.unit_in" style="width:200px" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="售出单位" prop="unit">
              <el-input v-model="saveProductForm.unit" style="width:200px" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="转换比例" prop="conversion">
              <el-input-number controls-position="right" :precision="2" :step="1" :min="0" v-model="saveProductForm.conversion" style="width:200px"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="备注" prop="comment">
              <el-input v-model="saveProductForm.comment" style="width:300px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveProductDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveProduct">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 分类列表（不变）
      categoryList: [],
      saveForm: {
        productList: [],
        supplier: '',
        default_time: ''
      },
      saveFormRules: {
        supplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
        default_time: [{ required: true, message: '请选择日期', trigger: 'change' }]
      },
      // 是否新增商品
      isProductAdd: true,
      saveProductDialogVisible: false,
      goodsList: [],
      // 添加新的商品
      saveProductForm: {
        category_id: '',
        category: '',
        goods_id: '',
        goods: '',
        sellable: 1,
        price_in: 0.00,
        unit_in: '',
        unit: '',
        conversion: 1,
        count_in: 1,
        total_amount: 0.00,
        comment: ''
      },
      // 添加表单的验证规则对象
      saveProductFormRules: {
        category_id: [
          { required: true, type: 'number', message: '请选择分类', trigger: 'change' }
        ],
        goods_id: [
          { type: 'number', required: true, message: '请选择商品', trigger: 'change' }
        ],
        price_in: [
          { type: 'number', required: true, message: '请输入价格', trigger: 'blur' }
        ],
        count_in: [
          { type: 'number', required: true, message: '请输入数量', trigger: 'blur' }
        ],
        conversion: [
          { type: 'number', required: true, message: '请输入转换比例', trigger: 'blur' }
        ]
      },
      modifyProductIndex: 0,
      // 是否需要重置goods
      isSet: 0
    }
  },
  mounted() {
    this.getCategoryList()
  },
  watch: {
    'saveProductForm.goods_id': {
      handler: function(val, oldval) {
        if (val) {
          let goodsDetail = {}
          goodsDetail = this.goodsList.find((item) => {
            return item.id === val
          })
          if (goodsDetail) {
            this.saveProductForm.goods = goodsDetail.name
            this.saveProductForm.sellable = goodsDetail.sellable
            this.saveProductForm.unit_in = goodsDetail.unit_in
            this.saveProductForm.unit = goodsDetail.unit
            this.saveProductForm.conversion = goodsDetail.conversion
            this.saveProductForm.price_in = goodsDetail.price_in
          }
        } else {
          this.saveProductForm.goods = ''
          this.saveProductForm.sellable = 1
          this.saveProductForm.unit_in = ''
          this.saveProductForm.unit = ''
          this.saveProductForm.conversion = 1
          this.saveProductForm.price_in = 0.00
        }
      }
    },
    'saveProductForm.category_id': {
      handler: function(val, oldval) {
        if (val) {
          this.saveProductForm.category = this.categoryList.find((item) => {
            return item.id === val
          }).category_name
          this.getGoodsList(val)
        } else {
          this.saveProductForm.category = ''
          this.goodsList = []
          this.saveProductForm.goods_id = ''
        }
      }
    },
    'saveProductForm.price_in': {
      handler: function(val, oldval) {
        this.saveProductForm.total_amount = val * this.saveProductForm.count_in
      }
    },
    'saveProductForm.count_in': {
      handler: function(val, oldval) {
        this.saveProductForm.total_amount = val * this.saveProductForm.price_in
      }
    }
  },
  methods: {
    // 获取分类
    async getCategoryList() {
      const { data: result } = await this.$http.get('/category')
      if (result.status !== 200) return this.$message.error(result.msg)
      this.categoryList = result.data
    },
    // 监听新增商品对话框的关闭事件
    saveProductDialogClosed() {
      this.isSet = 0
      if (this.isProductAdd) {
        this.$refs.saveProductFormRef.resetFields()
      }
    },
    async getGoodsList(category_id) {
      const params = {
        page: 1,
        pageSize: 100000,
        category_id: category_id,
        process: 0,
      }
      const { data: result } = await this.$http.get('/goods/list', { params: params })
      if (result.status === 200) {
        this.goodsList = result.data
        if (this.isSet) {
          this.saveProductForm.goods_id = ''          
        }
      }
    },
    // 显示商品对话框
    showProductAddDialog() {
      this.isProductAdd = true
      this.saveProductForm = {
        category_id: '',
        category: '',
        goods_id: '',
        goods: '',
        sellable: 1,
        price_in: 0.00,
        unit_in: '',
        unit: '',
        conversion: 1,
        count_in: 1,
        total_amount: 0.00,
        comment: ''
      }
      this.saveProductDialogVisible = true
      this.isSet = 1
    },
    // 点击按钮，添加商品
    saveProduct() {
      this.$refs.saveProductFormRef.validate(async (valid) => {
        if (!valid) return
        var product = this.$_.cloneDeep(this.saveProductForm)
        // 修改
        if (!this.isProductAdd) {
          this.saveForm.productList.splice(this.modifyProductIndex, 1, product)
          this.$message.success('修改商品成功！')
        } else {
          // 新增
          this.saveForm.productList.push(product)
          this.$message.success('添加商品成功！')
        }
        // 隐藏添加商品的对话框
        this.isSet = 0
        this.saveProductDialogVisible = false
      })
    },
    // 显示修改商品对话框
    showProductEditDialog(contact, index) {
      this.isProductAdd = false
      this.saveProductForm = this.$_.cloneDeep(contact)
      this.modifyProductIndex = index
      this.saveProductDialogVisible = true
    },
    // 删除商品
    async deleteProduct(product) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('删除该商品，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      this.saveForm.productList.splice(
        this.saveForm.productList.findIndex((existedProduct) => existedProduct === product),
        1
      )
      this.$message.success('删除商品成功！')
    },
    // 返回
    back() {
      this.$router.push({ 'name': 'material-list' })
    },
    // 点击按钮，保存入库单
    async handleSubmit() {
      this.$refs.saveFormRef.validate(async (valid) => {
        if (!valid) return
        // 循环验证
        const handleData = []
        let check = []
        let flag = 1
        this.saveForm.productList.forEach(element => {
          if ( flag === 1 && !element.goods_id) {
            this.$message.error('提交失败，请检测未选择商品')
            flag = 0
            return false;
          }
          // if ( flag === 1 && !element.price_in) {
          //   this.$message.error('提交失败，商品入库价格为0')
          //   flag = 0
          //   return false;
          // }
          if ( flag === 1 && !element.count_in) {
            this.$message.error('提交失败，商品数量为0')
            flag = 0
            return false;
          }
          if ( flag === 1 && !element.conversion) {
            this.$message.error('提交失败，转换比例不得为0')
            flag = 0
            return false;
          }
          if ( flag === 1 && check.indexOf(element.goods_id) !== -1) {
            this.$message.error('数据重复')
            flag = 0
            return false;
          }
          check.push(element.goods_id)
          handleData.push({
            goods_id: element.goods_id,
            count_in: element.count_in ? element.count_in : 0,
            price_in: element.price_in ? element.price_in : 0,
            comment: element.comment ? element.comment : '',
            conversion: element.conversion ? element.conversion : 1
          })
        })
        if (flag) {
          const { data: result } = await this.$http.post('/house/multi', {
            data: handleData, 
            supplier: this.saveForm.supplier,
            default_time: new Date(this.saveForm.default_time).toLocaleDateString().split('/').join('-'),
            process: 0
          })
          if (result.status !== 200) {
            return this.$message.error(result.msg)
          }
          this.$message.success('保存成功')
          this.$router.push({ name: 'material-purchase' })
        } else {
          return false
        }
      })
    }
  }
}
</script>